<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="检查名称" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入检查名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查类型" v-bind="validateInfos.inspectType">
	          <j-dict-select-tag v-model:value="formData.inspectType" dictCode="baseCheckType" placeholder="请选择检查类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查来源" v-bind="validateInfos.source">
            <a-input v-model:value="formData.source" placeholder="请输入检查来源" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="涉及危险源" v-bind="validateInfos.hazardName">
            <a-input v-model:value="formData.hazardName" placeholder="请输入涉及危险源" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="组织检查单位" v-bind="validateInfos.inspectionUnit">
            <a-input v-model:value="formData.inspectionUnit" placeholder="请输入组织检查单位" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="被检查单位" v-bind="validateInfos.jnitUnderInspection">
            <a-input v-model:value="formData.jnitUnderInspection" placeholder="请输入被检查单位" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查级别" v-bind="validateInfos.inspectionLevel">
            <j-dict-select-tag v-model:value="formData.inspectionLevel" dictCode="inspectionLevel" placeholder="请选择检查级别" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查种类" v-bind="validateInfos.inspectionType">
            <j-dict-select-tag v-model:value="formData.inspectionType" dictCode="inspectionType" placeholder="请选择检查种类" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="任务开始日期" v-bind="validateInfos.taskStartTime">
		        <a-date-picker placeholder="请选择任务开始日期" v-model:value="formData.taskStartTime" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="任务结束日期" v-bind="validateInfos.taskEndTime">
		        <a-date-picker placeholder="请选择任务结束日期" v-model:value="formData.taskEndTime" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查人" v-bind="validateInfos.examiner">
	          <j-select-user-by-dept v-model:value="formData.examiner" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="登记时间" v-bind="validateInfos.registrationTime">
		        <a-date-picker placeholder="请选择登记时间" v-model:value="formData.registrationTime" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col> 
        <a-col :span="24">
          <a-form-item label="审批状态" v-bind="validateInfos.bpmStatus">
	          <j-dict-select-tag v-model:value="formData.bpmStatus" dictCode="baseCheckBpmType" placeholder="请选择审批状态" :disabled="disabled"/>
          </a-form-item>
        </a-col>-->
        <a-col :span="24">
          <a-form-item label="审批人" v-bind="validateInfos.approver">
	          <j-select-user-by-dept v-model:value="formData.approver" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="说明" v-bind="validateInfos.remark">
	          <a-textarea v-model:value="formData.remark" :rows="4" placeholder="请输入说明" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否使用检查表" v-bind="validateInfos.isNot">
            <j-dict-select-tag type='radio' v-model:value="formData.isNot" dictCode="yn" placeholder="请选择是否使用检查表" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="附件" v-bind="validateInfos.attachments">
            <j-upload v-model:value="formData.attachments"  :disabled="disabled" ></j-upload>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="删除标识" v-bind="validateInfos.deleted">
            <j-dict-select-tag type='radio' v-model:value="formData.deleted" dictCode="yn" placeholder="请选择删除标识" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="24">
          <a-form-item label="任务状态" v-bind="validateInfos.status">
	          <j-dict-select-tag v-model:value="formData.status" dictCode="task_status" placeholder="请选择任务状态" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <a-col v-if="showFlowSubmitButton" :span="24" style="width: 100%;text-align: center;">
          <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="submitForm">提 交</a-button>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSelectUserByDept from '/@/components/Form/src/jeecg/components/JSelectUserByDept.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../TbBaseCheckPlan.api';
  import { Form } from 'ant-design-vue';
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        name: '',   
        inspectType: '',   
        hazardName: '',   
        jnitUnderInspection: '',   
        taskStartTime: '',   
        taskEndTime: '',   
        examiner: '',   
        registrationTime: '',   
        bpmStatus: '',   
        approver: '',   
        attachments: '',   
        remark: '',   
        source: '',   
        isNot: '',   
        inspectionUnit: '',   
        inspectionLevel: '',   
        inspectionType: '',   
        deleted: '',   
        status: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    examiner: [{ required: true, message: '请输入检查人!'},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
  const formRef = ref();
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  onMounted(()=>{
    initFormData();
  });
  //渲染流程表单数据
  const queryByIdUrl = '/TbBaseCheckPlan/tbBaseCheckPlan/queryById';
  async function initFormData(){
    if(props.formBpm === true){
      let params = {id: props.formData.dataId};
      const data = await defHttp.get({url: queryByIdUrl, params});
      //设置表单的值
      edit({...data});
    }
  }
  // 是否显示提交按钮
  const showFlowSubmitButton = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return true
      }
    }
    return false
  });
  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    
    /* 如果选择了审批人需要做审批操作，审批状态为暂存，如果没有选择审批人则直接生效，审批状态为通过*/
    console.log("-----model.approver-------"+model.approver)
    console.log("---------------------------");
    if (model.approver != null && model.approver != undefined && model.approver != '') {
      model.bpmStatus = "baseCheckBpmType01"
    } else {
      model.bpmStatus = "baseCheckBpmType02"
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
